package com.zretc.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.zretc.dao.FoodDao;
import com.zretc.dao.impl.FoodDaoImpl;
import com.zretc.entity.Food;
import com.zretc.service.FoodService;
import com.zretc.service.impl.FoodServiceImpl;
import com.zretc.tools.PageData;

/**
 * Servlet implementation class FoodServlet
 */
@WebServlet("/FoodServlet")
@MultipartConfig
public class FoodServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	FoodDao foodDao = new FoodDaoImpl();

	FoodService foodService = new FoodServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1设置请求编码
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		
		


		
		
		// 标记当前为何种操作的变量
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		System.out.println("op:" + op);
		if ("".equals(op)) {
			doQuery(request, response);

		} else if ("add".equals(op)) {
			doAdd(request, response);

		} else if ("queryByPage".equals(op)) {
			// 分页有关的查询 数据处理 页面跳转等
			doQueryByPage(request, response);

		}else if ("del".equals(op)) {
			// 分页有关的查询 数据处理 页面跳转等
			dodel(request, response);

		}else if ("update".equals(op)) {
			// 分页有关的查询 数据处理 页面跳转等
			doupdate(request, response);

		}
	}
	
	private void doupdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int foodid=Integer.parseInt(request.getParameter("foodid"));
		String foodname = request.getParameter("foodname");
		String foodimg = request.getParameter("foodimg");
		String foodcontent = request.getParameter("foodcontent");
		double price =Double.parseDouble(request.getParameter("price"));
		int sales = Integer.parseInt(request.getParameter("sales"));
		String listtime = request.getParameter("listtime");
		String offtime = request.getParameter("offtime");
		int fdtypeid = Integer.parseInt(request.getParameter("fdtypeid"));
		// 2构造一个newstype对象
		Part file = request.getPart("foodimg");
		System.out.println("file:"+file);
		String pathString = request.getRealPath("/img/");
		pathString += file.getSubmittedFileName();
		System.out.println(pathString);
		Food food = new Food(foodid, foodname, pathString, foodcontent, price, sales, listtime, offtime, fdtypeid);

		
		boolean flag = foodService.updateFood(food);
		// 4根据返回结果进行转发或者提示等
		if (flag) {
			// 转发到显示servelt上进行查询，直接调用doQuery的方法即可。
			doQuery(request, response);
		} else {
			// 转发到回到newstype增加的页面
			//失败分两种情况，一种是如果名字重复；另外可能发生异常
			request.setAttribute("msg", "修改失败！请重新修改。");
			request.getRequestDispatcher("updatefood.jsp").forward(request, response);
			
		}
		
	}

	private void dodel(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("utf-8");
		int foodid=Integer.parseInt(request.getParameter("foodid"));
		System.out.println("要删除：foodid："+foodid);
		boolean flag=foodService.delFood(foodid);
		if (flag) {
			response.getWriter().append("<script>alert('删除成功');location.href='http://localhost:8080/sfs0428/FoodServlet'</script>");
		}else {
			response.getWriter().append("<script>alert('删除失败');location.href='http://localhost:8080/sfs0428/FoodServlet'</script>");
		}
	}

	/**
	 * 增加的操作
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 添加类型的操作
		// 1获取请求的参数,要先判断是否为空[需要有服务器端验证]
		String foodname = request.getParameter("foodname");
		String foodimg = request.getParameter("foodimg");
		String foodcontent = request.getParameter("foodcontent");
		double price =Double.parseDouble(request.getParameter("price"));
		int sales = Integer.parseInt(request.getParameter("sales"));
		String listtime = request.getParameter("listtime");
		String offtime = request.getParameter("offtime");
		int fdtypeid = Integer.parseInt(request.getParameter("fdtypeid"));
		// 2构造一个newstype对象
		Part file = request.getPart("foodimg");
		System.out.println("file:"+file);
		String pathString = request.getRealPath("/img/");
		pathString += file.getSubmittedFileName();
		System.out.println(pathString);
		Food food = new Food( foodname, pathString, foodcontent, price, sales, listtime, offtime, fdtypeid);

		
		boolean flag = foodService.addFood(food);
		// 4根据返回结果进行转发或者提示等
		if (flag) {
			// 转发到显示servelt上进行查询，直接调用doQuery的方法即可。
			doQuery(request, response);
		} else {
			// 转发到回到newstype增加的页面
			//失败分两种情况，一种是如果名字重复；另外可能发生异常
			request.setAttribute("msg", "增加失败！请重新添加。");
			request.getRequestDispatcher("addfood.jsp").forward(request, response);
			
		}
	}
	/**
	 * 模糊查询的方法
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doQuery(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		System.out.println("bbb");
		// 3 调用 dao的方法
		List<Food> list = foodDao.getFood(keywords);
		System.out.println("list:"+list);
		// 4传递list给jsp
		request.setAttribute("list", list);
		// 5 转发
		request.getRequestDispatcher("mealManage.jsp").forward(request, response);
		System.out.println("aaa");
	}
	
	
	/**
	 * 模糊查询 分页
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void doQueryByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认值为1
		int page = 1;
		// 每页记录数默认为10
		int pageSize = 3;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}

		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}

		// 3 调用 Service的方法
		PageData<Food> pd = foodService.getFoodByPage(page, pageSize, keywords);

		// 4传递PageData对象给jsp
		request.setAttribute("pd", pd);
		
		//4.-1转发回来的时候，我们将查询关键字也存储在request范围内
		request.setAttribute("keywords", keywords);

		// 5 转发
		request.getRequestDispatcher("mealManage.jsp").forward(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
